package com.sxhuayuan.parking.controller.admin;

import com.alibaba.fastjson.JSON;
import com.sxhuayuan.parking.compenent.domain.KeyValue;
import com.sxhuayuan.parking.compenent.domain.SystemData;
import com.sxhuayuan.parking.compenent.web.RespMessage;
import com.sxhuayuan.parking.controller.BaseController;
import com.sxhuayuan.parking.dto.SumDTO;
import com.sxhuayuan.parking.service.AgentService;
import com.sxhuayuan.parking.service.OrderService;
import com.sxhuayuan.parking.service.ParkingLotService;
import com.sxhuayuan.parking.service.RedisService;
import com.sxhuayuan.parking.utils.DateUtils;
import com.sxhuayuan.parking.utils.SystemInfoUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 统计
 */
@RestController("adminStatisticsController")
@RequestMapping("/admin/statis")
public class StatisticsController extends BaseController {

	@Resource(name = "orderServiceImpl")
	OrderService orderService;

	@Resource(name = "agentServiceImpl")
	AgentService agentService;

	@Resource(name = "parkingLotServiceImpl")
	ParkingLotService parkingLotService;

	@Resource(name = "redisServiceImpl")
	RedisService redisService;

	/**
	 * 环境信息保存在Redis里的key
	 */
	private static final String REDIS_ENVIRONMENTAL_INFORMATION = "environmental_information";

	private static final String REDIS_COUNT_ORDER = "admin_count_order";

	/**
	 * 统计昨天与本月订单金额
	 * 
	 * @return
	 */
	@GetMapping("/order")
	public RespMessage countOrder() {

		String string = redisService.getString(REDIS_COUNT_ORDER);
		if (string != null) {
			List<SumDTO> sumDTOS = JSON.parseArray(string, SumDTO.class);
			return RespMessage.builder().success().setDatas(sumDTOS).build();
		} else {
			Date yesterdayStartTime = DateUtils.getStartTimeOfOneday(-1);
			Date startTimeOfCurrentMonth = DateUtils.getStartTimeOfCurrentMonth();
			Date yesterdayEndTime = DateUtils.getEndTimeOfOneday(-1);
			// 本月订单统计
			SumDTO sumDTO = orderService.countByDataTime(startTimeOfCurrentMonth, yesterdayEndTime, null);

			// 昨日订单统计
			SumDTO sumDTO1 = orderService.countByDataTime(yesterdayStartTime, yesterdayEndTime, null);

			List<SumDTO> list = new ArrayList<>();
			list.add(sumDTO);
			list.add(sumDTO1);

			String s = JSON.toJSONString(list);
			redisService.saveString(REDIS_COUNT_ORDER, s, DateUtils.nowToTomorrowSecond());

			return RespMessage.builder().success().setDatas(list).build();
		}

	}

	/**
	 * 统计代理数量和车场数量
	 * 
	 * @return
	 */
	@GetMapping("/agentandparkinglot")
	public RespMessage countAgentAndParkingLot() {
		Long agent = agentService.countAll(null);
		Long parkingLot = parkingLotService.countAll(null);
		List<Long> list = new ArrayList<>();
		list.add(agent);
		list.add(parkingLot);
		return RespMessage.builder().success().setDatas(list).build();
	}

	/**
	 * 订单统计
	 *
	 * @param type
	 *            时间格式化类型
	 * @param startTime
	 *            起始时间
	 * @param endTime
	 *            终止时间
	 * @param id
	 *            车场id
	 * @return 统计结果 0:时间 1:订单数量 3:订单金额
	 */
	@PostMapping("/echars/countorder")
	public RespMessage cylindricalGraph(@RequestParam String type, @RequestParam String startTime, @RequestParam String endTime, Long id) {
		String sn = null;
		if (id != null) {
			sn = parkingLotService.findOne(id).getSn();
		}
		String formatType = null;
		switch (type) {
		case "date":
			formatType = "%m-%d";
			break;
		case "month":
			formatType = "%Y-%m";
			break;
		default:
			RespMessage.error("查询类型错误");
		}
		List<Map<String, Object>> map = orderService.findCountByDateTime(formatType, startTime, endTime, sn, null);
		return successResp(map);
	}

	/** 根据时间查询车场订单饼图数据 */
	@PostMapping("/echars/parkinglot")
	public RespMessage parkingLotOrder(@RequestParam String startTime, @RequestParam String endTime) {
		List<Map<String, Object>> map = orderService.findParkingLotByDateTime(startTime, endTime, null);
		return successResp(map);
	}

	/**
	 * 进度环数据查询
	 *
	 * @return
	 */
	@GetMapping("/annular/datas")
	public RespMessage getCount() {
		ArrayList<SystemData> list = new ArrayList<>();
		double jvmCount = SystemInfoUtils.getJvmThreadLoad();
		String jvmText = "运行流畅";
		if (jvmCount >= 90) {
			jvmText = "系统阻塞";
		}
		list.add(new SystemData("JVM线程负载", jvmCount, jvmText));

		list.add(new SystemData("CPU负载", SystemInfoUtils.getSystemCpuLoad(), SystemInfoUtils.getCpuCore() + " 核心"));

		String memoryText = SystemInfoUtils.getUsedMemory() + "/" + SystemInfoUtils.getTotalMemorySize() + "(MB)";

		list.add(new SystemData("内存利用率", SystemInfoUtils.getMemoryCount(), memoryText));

		String diskText = SystemInfoUtils.getDiskUseSpace() + "/" + SystemInfoUtils.getDiskTotalSpace() + "(GB)";

		list.add(new SystemData("磁盘使用率", SystemInfoUtils.getDiskUtilizationRate(), diskText));

		return RespMessage.builder().success().setDatas(list).build();

	}

	/**
	 * 环境信息查询
	 *
	 * @return
	 */
	@GetMapping("/environmentalinformation")
	public RespMessage parameters() {

		/* 先进Redis查询 */
		String string = redisService.getString(REDIS_ENVIRONMENTAL_INFORMATION);

		if (string != null) {
			List<KeyValue> keyValues = JSON.parseArray(string, KeyValue.class);
			return RespMessage.builder().success().setDatas(keyValues).build();
		}

		List<KeyValue> list = getParameters();
		return RespMessage.builder().success().setDatas(list).build();

	}

	private List<KeyValue> getParameters() {
		List<KeyValue> list = new ArrayList<>();
		list.add(new KeyValue("数据库", "mysql 5.7"));
		list.add(new KeyValue("Redis版本", "5.0"));
		list.add(new KeyValue("CPU核数", (long) Runtime.getRuntime().availableProcessors()));
		list.add(new KeyValue("java版本", System.getProperty("java.version")));
		list.add(new KeyValue("Java安装目录", System.getProperty("java.home")));
		list.add(new KeyValue("Java虚拟机实现名称", System.getProperty("java.vm.name")));
		// 转化为json串
		String s = JSON.toJSONString(list);
		redisService.saveString(REDIS_ENVIRONMENTAL_INFORMATION, s, 60 * 60 * 24);
		return list;
	}

	/**
	 * 系统信息查询
	 *
	 * @param req
	 * @return
	 */
	@GetMapping("/systeminformation")
	public RespMessage systemInformation(HttpServletRequest req) {

		List<KeyValue> list = new ArrayList<>();
		list.add(new KeyValue("客户端ip", req.getRemoteAddr()));
		list.add(new KeyValue("服务端ip", req.getLocalAddr()));
		list.add(new KeyValue("操作系统名称", System.getProperty("os.name")));
		list.add(new KeyValue("操作系统版本", System.getProperty("os.version")));
		list.add(new KeyValue("操作系统架构", System.getProperty("os.arch")));
		list.add(new KeyValue("用户主目录", System.getProperty("user.home")));
		list.add(new KeyValue("工作目录", System.getProperty("user.dir")));
		return RespMessage.builder().success().setDatas(list).build();
	}
}
